using UnityEngine;

public class BagItemViewCreator : PersistentSingleton<BagItemViewCreator>
{
    // ======================
    // 对外公开的两个重载方法（带默认 EventMode）
    // ======================

    // 默认 EventMode 为 Default
    public IBagItemView CreateView(BagItemData bagItemData, Transform parent, EventMode mode = EventMode.Default)
    {
        return CreateInternal(bagItemData, parent, mode);
    }

    public IBagItemView CreateView(BagItemData bagItemData, GameObject parentObj, EventMode mode = EventMode.Default)
    {
        return CreateInternal(bagItemData, parentObj?.transform, mode);
    }

    // ======================
    // 内部统一逻辑
    // ======================
    private IBagItemView CreateInternal(BagItemData bagItemData, Transform parent, EventMode mode)
    {
        if (bagItemData == null)
        {
            Debug.LogError("BagItemData is null, cannot create view.");
            return null;
        }

        if (parent == null)
        {
            Debug.LogError("Parent transform is null.");
            return null;
        }

        // 拼接 Resources 路径
        string path = bagItemData.Path;
        GameObject prefab = Resources.Load<GameObject>(path);

        if (prefab == null)
        {
            Debug.LogError($"Prefab not found at path: {path}");
            return null;
        }

        // 实例化到 parent 下
        GameObject instance = Object.Instantiate(prefab, parent);

        // 获取实现了 IBagItemView 的组件
        IBagItemView view = instance.GetComponent<IBagItemView>();
        if (view == null)
        {
            Object.Destroy(instance);
            Debug.LogError($"Prefab at {path} does not implement IBagItemView.");
            return null;
        }

        // 初始化
        view.Setup(bagItemData, mode);

        return view;
    }
}
